package com.knr.client;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.HTTPRequest;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class KREngine extends AbsolutePanel {

	private HTMLPanel html;

	/**
	 * This is the entry point method.
	 */
	public KREngine() {
		super();
		GWT.log("Loading KnR Engine", null);
		html = new HTMLPanel("KnR");
		html.setTitle("KnR Enhanced Surfing Experience");

		Element body = RootPanel.getBodyElement();
		KRTextParser parser = new KRTextParser();
		
			try {
				KRParaElems krp = new KRParaElems();
				KRJSUtils.enableAccessAcrossDomains();
				KRJSUtils.findAllParagraphElements(krp);
				List pList = krp.getElements();
				Iterator it = pList.iterator();
				/* pList has all the paragraph Elements */
				while (it.hasNext()) {
					Set keyWordSet = parser.findKeyWords((String)it.next());
					Iterator keyWordIterator = keyWordSet.iterator();
					while(keyWordIterator.hasNext())
					{
						String strToReplace = (String)keyWordIterator.next();
						KRResponseHandler handler = new KRResponseHandler(strToReplace);
						//Window.alert(strToReplace);						
						//boolean value = HTTPRequest.asyncGet("http://video.google.com/videosearch?q=" + strToReplace, handler);
						boolean value = KRJSUtils.asyncGetImpl("http://video.google.com/videosearch?q=" + strToReplace, handler);
						System.out.println("Query str " + strToReplace);
						//System.out.println("query " + strToReplace + " result " + handler.getResult());
						//KRJSUtils.replaceString(strToReplace, handler.getResult());
					}
					//GWT.log((String) it.next(), null);
				}
			} catch (Exception e) {
				Window.alert(e.getMessage());
				GWT.log("error", e);
			}
	}

}
